package com.eric.product.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.eric.product.entity.Product;
import com.eric.product.service.ProductService;
import entity.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author:Eric
 * @date:2021/7/7
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public CommonResult insert(@RequestBody Product product) {
        log.info("insert :{}", product.toString());
        productService.save(product);
        return CommonResult.success("success");
    }

    @PutMapping
    public CommonResult update(@RequestBody Product product) {
        log.info("update :{}", product.toString());
        productService.updateById(product);
        return CommonResult.success("success");
    }

    @DeleteMapping("/{id}")
    public CommonResult delete(@PathVariable Long id) {
        log.info("delete id:{}", id);
        productService.removeById(id);
        return CommonResult.success("success");
    }

    @GetMapping("/{id}")
    @SentinelResource(value = "product/getOne", fallback = "getOneFallback")
    public CommonResult getOne(@PathVariable Long id) {
        log.info("delete id:{}", id);
        Product product = productService.getById(id);
        return CommonResult.success(product, "success");
    }

    @PostMapping("/reduce")
    public CommonResult reduce(@RequestBody Product product){
        log.info("reduce product:{}", product.toString());
        productService.reduce(product);
        return CommonResult.success("success");
    }

    /**
     * 服务熔断处理方法
     *
     * @param id
     * @return
     */
    public CommonResult getOneFallback(Long id) {
        log.info("服务降级 id:{}", id);
        return CommonResult.failed("服务熔断了！");
    }

}
